//
//  UserDBManager.m
//  Order
//
//  Created by funny on 12-3-22.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "UserDBManager.h"


@implementation UserDBManager

@synthesize nowUserName;

static UserDBManager *sharedUserDBManager = nil;

- (id)init{
    if (self = [super init])  {
		nowUserName = [@"" copy];
		
		users = [[NSMutableDictionary alloc] init];
		
		[users setObject:[UserDB userDBWithID:1 andName:@"admin" andKey:@"admin" andJurisdiction:UserJurisdictionTypeAdmin] forKey:@"admin"];
		[users setObject:[UserDB userDBWithID:2 andName:@"001" andKey:@"001" andJurisdiction:UserJurisdictionTypePlain] forKey:@"001"];
		[users setObject:[UserDB userDBWithID:3 andName:@"002" andKey:@"002" andJurisdiction:UserJurisdictionTypePlain] forKey:@"002"];
	}
	return self;
}

+ (UserDBManager *)sharedUserDBManager{
    @synchronized(self){
		if  (sharedUserDBManager == nil){
            [[self alloc] init];
        }
    }
	
	return  sharedUserDBManager;
}

+ (id)allocWithZone:(NSZone *)zone{
    @synchronized(self){
		if (sharedUserDBManager == nil){
            sharedUserDBManager = [super allocWithZone:zone];
			
			return  sharedUserDBManager;
        }
    }
	
	return  nil;
}

- (BOOL)loginWithName:(NSString *)newName andKey:(NSString *)newKey{
	UserDB *nowUser = [users objectForKey:newName];
	
	if (nowUser && [nowUser.key isEqualToString:newKey]) {
		nowUserName = [newName copy];
		
		return YES;
	}
	
	UIAlertView *alert=[[[UIAlertView alloc] initWithTitle:@"登录失败" message:@"用户名密码错误！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
	[alert show];
	
	return NO;
}

- (void)signOut{
	nowUserName = [@"" copy];
}

- (NSInteger)nowUserID{
	UserDB *nowUser = [users objectForKey:nowUserName];
	
	if (nowUser) {
		return nowUser.userID;
	}
	
	return 1;
}

- (UserJurisdictionType)nowUserJurisdictionType{
	UserDB *nowUser = [users objectForKey:nowUserName];
	
	if (nowUser) {
		return nowUser.jurisdictionType;
	}
	
	return UserJurisdictionTypePlain;
}
		 
- (void)dealloc {
	[users release];
	[nowUserName release];
	
    [super dealloc];
}

@end
